package com.xz.xzutils.utils;

import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.SocketException;

/**
 * @author DONG.WANG17@HAND-CHINA.COM
 * @since 2025-02-16 19:21
 */
public class SocketUtil {
    private SocketUtil() {
    }

    public static boolean isPortBind(int port) {
        if (port < 1 || port > 65535) {
            throw new IllegalArgumentException("端口号无效: " + port);
        }

        try (ServerSocket serverSocket = new ServerSocket()) {
            // 设置地址重用避免TIME_WAIT状态影响
            serverSocket.setReuseAddress(false);
            // 绑定端口检测（立即释放）
            serverSocket.bind(new java.net.InetSocketAddress("127.0.0.1", port), 1);
            return false;
        } catch (BindException e) {
            // 明确捕获端口被占用的异常
            return true;
        } catch (SocketException e) {
            // 处理其他Socket异常（如权限不足）
            System.err.println("端口检测异常: " + e.getMessage());
            return true;
        } catch (IOException e) {
            // 其他IO异常视为未绑定
            return false;
        }
    }
}
